package cn.jiannan;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author wuyuhong
 * @date 2021/05/31 23:03
 **/
@RestController
public class FileUploadController  {
    SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");//这里不能少/，为了和别的字符串拼接
    @PostMapping("/upload")
    //MultipartFile file中的file要和静态界面的名字对应上
    public String upload(MultipartFile file, HttpServletRequest req) {
        String realPath = req.getServletContext().getRealPath("/");
        String format = sdf.format(new Date());
        //String path = "D:\\tool\\Typora\\notebook"; //最终路径
        String path = realPath+format; //最终路径
        File folder = new File(path);
        if (!folder.exists()) {
            //不存在，创建dirs是创建多层
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();//原本的文件名，后缀
        System.out.println("oldName"+oldName);
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));//文件保存目录，文件名称
            String s = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format+newName;
            //scheme是请求协议，serverName，也就是localhost,port是端口号,format是日期
            return  s;

        } catch (IOException e) {
            e.printStackTrace();
        }
return  "";

    }
}

